from django.shortcuts import render, redirect, HttpResponse
from django.contrib.auth.decorators import login_required
from .models import BookModel


# Create your views here.

def book_list(request):
    books = BookModel.objects.all().order_by('hot')
    return render(request, 'index1.html', {
        "books": books,
    })


def book_detail(request, id):
    book = BookModel.objects.get(id=id)
    borrowers = book.borrower.all()
    return render(request, 'detail.html', {
        "book": book,
        "borrowers": borrowers,
    })


@login_required(login_url='userprofile:login')
def book_borrow(request, id):
    book = BookModel.objects.get(id=id)
    borrowers = book.borrower.all()
    if book.nums > 0:
        if request.user not in borrowers:
            book.nums -= 1
            book.hot += 1
            book.borrower.add(request.user)
            book.save(update_fields=['nums', 'hot'])
            return render(request, 'detail.html', {
                "book": book,
            })
        else:
            return HttpResponse("这本书您已经借过了")
    else:
        return HttpResponse("借书出现错误:在馆书籍为0")


@login_required(login_url='userprofile:login')
def book_borrow_list(request):
    user = request.user
    books = user.bookmodel_set.all()
    return render(request, "borrow_list.html", {
        "books": books,
    })


@login_required(login_url='userprofile:login')
def book_return(request, book_id):
    book = BookModel.objects.get(id=book_id)
    user = request.user
    book.borrower.remove(user)
    book.nums += 1
    book.save(update_fields=['nums'])
    return redirect("bookcms:blist")
